<template>
  <el-popover
    placement="bottom-start"
    trigger="click">
    <el-tree
      ref="tree"
      :data="tree"
      :props="treeKey"
      :accordion="true"
      @node-click="treeClick">
    </el-tree>
    <el-input slot="reference"
              clearable
              v-model="label"
              :placeholder="placeholder"
              suffix-icon="el-icon-search"
              :size="size">
    </el-input>
  </el-popover>
</template>

<script>
import util from '@/libs/util'

export default {
  name: 'index',
  props: {
    // eslint-disable-next-line vue/require-valid-default-prop
    tree: { type: Array, default: [] },
    // eslint-disable-next-line vue/require-valid-default-prop
    list: { type: Array, default: [] },
    placeholder: { type: String, default: '' },
    size: { type: String, default: '' },
    value: { type: String, default: '' },
    topValue: { type: String, default: '0' },
    selectedTree: { type: Function }
  },
  model: {
    prop: 'value',
    event: 'checked'
  },
  watch: {
    value (v) {
      this.sysLabel(v)
    }
  },
  data () {
    return {
      label: '',
      obj: {},
      treeKey: {
        children: 'children',
        label: 'name'
      }
    }
  },
  computed: {
  },
  created () {
    this.sysLabel(this.value)
  },
  methods: {
    treeClick (e) {
      // console.info('获取到选中', e)
      // this.label = e.name
      this.setValue(e.id)
    },
    setValue (v) {
      this.$emit('checked', v)
    },
    querySelected (array, v) {
      return (array && array.length && array.length > 0 && array.find(e => e.id === v)) || undefined
    },
    sysLabel (v) {
      const obj = this.querySelected(this.list, v)
      this.selectedTree(obj)
      if (util.isNotBlank(v) && obj && obj.name) {
        this.label = obj.name
        return
      }
      this.label = ''
    }
  }
}
</script>

<style scoped>

</style>
